package com.ddstation.common.controller;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.ddstation.common.model.ImageModel;
import com.ddstation.common.service.ImageService;
import com.ddstation.common.util.UrlFilesToZip;
import com.ddstation.crm.login.bean.SessionLoginData;
import com.ddstation.sewage.service.SewageService;
import sun.misc.BASE64Decoder;

@Controller @Lazy
public class DownLoadController {

	static BASE64Decoder decoder = new sun.misc.BASE64Decoder();

//	private static final Logger logger = LoggerFactory.getLogger(UrlFilesToZip.class);
	/**
	* 下载多个文件
	* @return
	*/
	@RequestMapping(value="invs_multipleDownLoad.do", method = RequestMethod.POST)
	public void multipleDownLoadEvent(
			@RequestParam String reportImgId,
			@RequestParam String institutionId, 
			@RequestParam String destFileName, 
			HttpServletResponse response,
			HttpSession session)
		throws ClientProtocolException, IOException {
		
        SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY );
        // session中卫监所的基础信息传入service
        if ( StringUtils.isBlank(reportImgId)){
        	return;
        }
        // 访问权限check(防止异常调用)
 		if ( !sewageService.checkAccessAuthority(loginData.getInstitution().getId(),institutionId) ){
 			return;
 		}
		
		
		List<ImageModel> urlList = imageService.fetchImage(reportImgId);
		try {
			String filename = new String((destFileName+".zip").getBytes("UTF-8"), "ISO8859-1");//控制文件名编码
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			ZipOutputStream zos = new ZipOutputStream(bos);
			UrlFilesToZip s = new UrlFilesToZip();
			int idx = 1;
			String postfix = "";
			for (ImageModel oneFile : urlList) {
				String objKey = oneFile.getObjKey();
				if (!(objKey == null || objKey.indexOf(".") == -1)){
					//如果图片地址为null或者地址中没有"."就返回""
					postfix = objKey.substring(objKey.lastIndexOf(".") + 1).trim().toLowerCase();
				}
				if(StringUtils.isNotBlank(postfix)) {
					postfix = "."+postfix;
				}else{//设置默认后缀为jpg
					postfix = ".jpg";
				}

				zos.putNextEntry(new ZipEntry(destFileName + idx+postfix));
				//图片是base64
				String base64String = oneFile.getOriginImgUrl();
				if(StringUtils.isNotBlank(base64String)){
					base64String = base64String.substring(22, base64String.length());
				}
				byte[] bytes = decoder.decodeBuffer(base64String);
				//图片是ossurl
//				byte[] bytes = s.getImageFromURL(oneFile.getOriginImgUrl());
				zos.write(bytes, 0, bytes.length);
				zos.closeEntry();
				idx++;
			}
			zos.close();
			response.setContentType("application/octet-stream; charset=utf-8");
			// response.setContentType("application/force-download");// 设置强制下载不打开
			response.addHeader("Content-Disposition", "attachment;fileName=" + filename);// 设置文件名
			response.setHeader("Set-Cookie", "fileDownload=true; path=/"); // jQuery.fileDownload.js 文件下 成功响应
			OutputStream os = response.getOutputStream();
			os.write(bos.toByteArray());
			os.close();
		} catch (FileNotFoundException ex) {
//			logger.error("FileNotFoundException", ex);
		} catch (Exception ex) {
//			logger.error("Exception", ex);
		}
	}
	
	@Inject private ImageService imageService;
	@Inject private SewageService sewageService;
}

 